#include "MyTpThread.h"
#include <QDebug>
#include <QStringList>
#include <QThread>
// void WorkerThread::run(){
//          QString result;
//          /* ... here is the expensive or blocking operation ... */
//          emit resultReady(result);
// }

void MyTpThread::startWorkInAThread()
{
//      WorkerThread *workerThread = new WorkerThread(this);
//      connect(workerThread, &WorkerThread::resultReady, this, &MyTpThread::handleResults);
//      connect(workerThread, &WorkerThread::finished, workerThread, &MyTpThread::deleteLater);
//      workerThread->start();
}

MyTpThread::MyTpThread() 
{
     qDebug()<<"Thread constructor ID:"<<QThread::currentThreadId();
    this->begin=false;
    this->isOpen=false;
    this->pmyport=NULL;
    this->old_value=-99999;
    m_abort=false;
}
void MyTpThread::started()
{
    run();
}
void MyTpThread::run()
{
    qDebug()<<"Thread run ID:"<<QThread::currentThreadId();
    if(this->pmyport!=NULL) delete this->pmyport;
    pmyport=new QSerialPort();
    pmyport->setPortName("COM1");
    pmyport->setBaudRate(QSerialPort::Baud1200);
    pmyport->setDataBits(QSerialPort::Data7);
    pmyport->setParity(QSerialPort::OddParity);
    pmyport->setStopBits(QSerialPort::OneStop);
    pmyport->setFlowControl(QSerialPort::NoFlowControl);
    if (pmyport->open(QIODevice::ReadWrite)) {
        qDebug()<<"open";
        this->isOpen=true;
        QObject::connect(pmyport,SIGNAL(readyRead()), this, SLOT(onReady()));
    }else{
        this->isOpen=false;
    }
}
void MyTpThread::parse(QString str)
{
    QString str1;
    str1.append(this->last);
    str1.append(str);
    QStringList list1 = str1.split(QLatin1Char('\r'));
    if(this->begin){
        this->last=list1.at(list1.size()-1);
        if (list1.size()>1){
            this->top=list1.at(list1.size()-2);
            read();
        }
    }else{
        if (list1.size()>1){
            this->begin=true;    
            this->top=list1.at(list1.size()-2);
            this->last=list1.at(list1.size()-1);
            read();
        }
    }
}
void MyTpThread::onReady()
{
    const QByteArray data = pmyport->readAll();
    if(data.length()>0) {
        QString str1(data);
        this->parse(str1);
    }else{
        qDebug()<<"data len <=0";
    }

}
void MyTpThread::read()
{
    // QString msg=this->top;
    // qDebug()<<msg;
    // qDebug()<<"Thread run ID:"<<QThread::currentThreadId();
    if (this->top.indexOf("g")==-1) return;
    QString sign=this->top.mid(1,1);
    QString v=this->top.mid(2,9);
    double r=v.toDouble();
    // qDebug()<<sign;
    if (sign=="-")
        r=-r;
   if(old_value!=r){
        old_value=r;
        qDebug()<<r;
        emit dataArrive(r);
    }
}
MyTpThread::~MyTpThread()
{
    // pmyport->close();
    // delete pmyport;
}
